const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const to = app.require("lib/awaitTo")

module.exports = {
    data: {
        collectionLoading: false
    },
    async collection() {
        // 收藏操作
        if (this.data.collectionLoading) return
        const {
            _id,
            isCollection,
            collectionNum
        } = this.data.post
        // 进入加载状态，阻止用户频繁点击
        this.setData({
            collectionLoading: true
        })
        const [err] = await to(db.collection("post")
            .doc(_id)
            .update({
                data: {
                    collection: isCollection ? _.pull(this.data.user._id) : _.push(this.data.user._id),
                    collectionNum: _.inc(isCollection ? -1 : 1)
                }
            }))
        this.setData({
            collectionLoading: false
        })
        if (err) { return }
        !isCollection && this.addMessage({ type: "collection" })
        this.setData({
            "post.isCollection": !isCollection,
            "post.collectionNum": isCollection ? collectionNum - 1 : collectionNum + 1
        })
        wx.showToast({
            title: isCollection ? '取消收藏' : '收藏成功',
            icon: "none"
        })
    },
}